//引入列表接口
import { goodscount, goodslist } from '@/request/api'

//封装一个接口类型
interface StateMenu {
    goodsList: Array<object>
    pageSize?: any,
    pageNum?: any,
    count?: any
}
let state = {
    goodsList: [],
    //页面显示的条数 每次只请求3条
    pageSize: 3,
    //页码
    pageNum: 1,
    //总条数
    count: 0
}
let mutations = {
    //修改列表
    GETGOODSLIST(state: StateMenu, playload: any) {
        state.goodsList = playload
    },
    //修改总条数
    GETGOODSCOUNT(state: StateMenu, playload: any) {
        state.count = playload
    },
    //合法修改页码
    GETPAGE(state: StateMenu, playload: any) {
        state.pageNum = playload
    }
}
let actions = {
    //获取列表的行动
    getgoodslist(context: any, playload: any) {
        goodslist({
            page: context.state.pageNum,
            size: context.state.pageSize,
        }).then((res: any) => {
            console.log(res,123123);
            if (res.code == 200) {
                let list = res.list ? res.list : []
                if (context.state.pageNum != 1 && list.length == 0) {
                    //修改页码并调用列表
                    context.dispatch('changePage', context.state.pageNum - 1)
                }

                context.commit('GETGOODSLIST', res.list)
            }
        }).catch(err => {
            console.log(err);
        })
    },
    //获取总条数的行动
    getcount(context: any) {
        goodscount().then((res: any) => {
            // console.log(res);
            if (res.code == 200) {
                //修改总条数
                context.commit('GETGOODSCOUNT', res.list[0].total)
            }
        }).catch(err => {
            console.log(err);

        })
    },
    //修改页码数的行动，并且重新获取列表
    changePage(context: any, playload: number) {
        //修改页码
        context.commit('GETPAGE', playload)
        //重新获取列表渲染页面
        context.dispatch('getgoodslist')
    }
}
let getters = {
    //返回总数据
    getList(state: StateMenu) {
        return state.goodsList
    },
    //返回页面显示的条数 固定的3条
    getPagesize(state: StateMenu) {
        return state.pageSize
    },
    //返回总条数
    getCount(state: StateMenu) {
        return state.count
    }
}
export default {
    state, mutations, actions, getters,
    //开启命名空间
    namespaced: true
}